/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.consumer;

import java.util.Collections;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.lang3.StringUtils;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.joda.time.DateTime;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;

import com.PredictionIoService;
import com.google.common.util.concurrent.AbstractExecutionThreadService;
import com.util.JsonMapper;

import io.prediction.Event;

public class Consumer extends AbstractExecutionThreadService implements HealthIndicator {
	  private  String topic;
	  private  KafkaConsumer<String, String> consumer;	
	  private  PredictionIoService predictionIoService;
	  private  JsonMapper jsonMapper = JsonMapper.nonDefaultMapper();	
	  public void setPredictionIoService(PredictionIoService predictionIoService) {
		this.predictionIoService = predictionIoService;
	 }
	  public Consumer(String topic,String kafkaServers) {
			super();
			this.topic = topic;
			Properties props = new Properties();
	        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaServers);
	        props.put(ConsumerConfig.GROUP_ID_CONFIG, "piwik_to_pio_consumer");
	        props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "true");
	        props.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "1000");
	        props.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, "30000");
	        props.put("key.serializer","org.apache.kafka.common.serialization.StringSerializer");
	        props.put("value.serializer","org.apache.kafka.common.serialization.StringSerializer");
	        consumer = new KafkaConsumer<>(props);
		}


	
	@Override
	public Health health() {
		return Health.up().withDetail(topic+" Consumer", this.state()).build();
	}

	@Override
	protected void run() throws Exception {
		while ( isRunning() ) {
			 consumer.subscribe(Collections.singletonList(this.topic));
		        ConsumerRecords<String, String> records = consumer.poll(1000);		        
		        for (ConsumerRecord<String, String> record : records) {
		        		send(record);          
		        }
		}	
		
	}


	@SuppressWarnings("unchecked")
	private void send(ConsumerRecord<String, String> record) {
		String eventId = "";
		while (StringUtils.isBlank(eventId)) {
			String entityType = record.topic().replace("piwik.", "");
			Event event = new Event();
			event.event("add_"+entityType);
			event.entityType(entityType);
			event.entityId(record.key());
			event.eventTime(new DateTime());
			event.properties(jsonMapper.fromJson(record.value(), Map.class));
			eventId = predictionIoService.creatEvent(event);
			
		}
	}
	

  
}
